/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package servlet;

import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.*;
import javax.servlet.http.*;
import session.BookFacadeLocal;
import stateless.BookBeanLocal;
import stateless.CartBeanLocal;

/**
 *
 * @author DELL
 */
public class control extends HttpServlet {
    CartBeanLocal cartBean;
    @EJB
    private BookBeanLocal bookBean;
    
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8"); 
        response.setHeader("content-type","text/html;charset=UTF-8");
        HttpSession session = request.getSession(true);
        if(request.getSession().getAttribute(request.getRemoteAddr() )==null){
            cartBean = lookupCartBeanLocal();
            request.getSession().setAttribute(request.getRemoteAddr(), this.cartBean);
        }
        else{
            cartBean = (CartBeanLocal)request.getSession().getAttribute(request.getRemoteAddr());
        } 
        String page = request.getParameter("page");
        String submit = request.getParameter("submit");
        RequestDispatcher dispatcher;
        switch (page) {
            case "index":
                dispatcher = request.getRequestDispatcher("index.jsp");
                dispatcher.forward(request,response);
                break;
            case "search":
                String bookName;
                switch (submit){
                    case "first":
                        bookName = new String(request.getParameter("bookName").getBytes("iso-8859-1"), "utf-8");
                        if(bookName.equals("")){
                            dispatcher = request.getRequestDispatcher("control?page=index");
                            dispatcher.forward(request,response);
                        }
                        else{
                            session.removeAttribute("bookDetail");
                            ArrayList<ArrayList<String>> bookDetail = this.bookBean.getBook(bookName);
                            session.setAttribute("bookDetail", bookDetail);
                            dispatcher = request.getRequestDispatcher("directory.jsp");
                            dispatcher.forward(request,response);
                        }
                        break;
                    case "again":
                        dispatcher = request.getRequestDispatcher("directory.jsp");
                        dispatcher.forward(request,response);
                        break;
                }
                break;
            case "directory":
                int id = Integer.parseInt(request.getParameter("bookID"));
                switch (submit){
                    case "detail":
                        ArrayList<String> detail = this.bookBean.findBook(id);
                        session.setAttribute("detail", detail);
                        dispatcher = request.getRequestDispatcher("detail.jsp");
                        dispatcher.forward(request,response);
                        break;
                    case "again":
                        int buyCount = Integer.parseInt(request.getParameter("buyCount"));
                        int maxCount = Integer.parseInt(request.getParameter("maxCount"));
                        if(buyCount > maxCount || buyCount <=0){
                            dispatcher = request.getRequestDispatcher("overRange.jsp");
                            dispatcher.forward(request,response);
                        }
                        else{
                            this.cartBean.addGood(id, buyCount);
                            dispatcher = request.getRequestDispatcher("control?page=search&submit=again");
                            dispatcher.forward(request,response);
                        }
                        break;
                }
                break;
            case "cart":
                if(submit.equals("detail")){
                    ArrayList<ArrayList<String>> goods = this.cartBean.getGoods();
                    ArrayList<ArrayList<String>> goodsDetail = new ArrayList<>();
                    for(ArrayList<String> good:goods){
                        int goodID =Integer.parseInt(good.get(0));
                        ArrayList<String> goodDetail = this.bookBean.findBook(goodID);
                        goodDetail.add(good.get(1));
                        goodsDetail.add(goodDetail);
                    }
                    session.setAttribute("goodsDetail", goodsDetail);
                    dispatcher = request.getRequestDispatcher("cart.jsp");
                    dispatcher.forward(request,response);
                }
                else if(submit.equals("clear")){
                    this.cartBean.cleanCart();
                    dispatcher = request.getRequestDispatcher("control?page=cart&submit=detail");
                    dispatcher.forward(request,response);
                }
                else if(submit.equals("order")){
                    ArrayList<String> orders = (ArrayList)session.getAttribute("orders");
                    if(orders == null) orders = new ArrayList<>();
                    
                    String date = new String(request.getParameter("date").getBytes("iso-8859-1"), "utf-8");
                    DecimalFormat df = new DecimalFormat("0.00");
                    String sumPrice = df.format(Double.valueOf(request.getParameter("sumprice")));
                    orders.add(date);
                    orders.add(sumPrice);
                    
                    this.cartBean.cleanCart();
                    session.setAttribute("orders",orders);
                    
                    dispatcher = request.getRequestDispatcher("order.jsp");
                    dispatcher.forward(request,response);
                }
                break;
            case "order":
                dispatcher = request.getRequestDispatcher("order.jsp");
                dispatcher.forward(request,response);
                break;
        }
        
        
       
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private CartBeanLocal lookupCartBeanLocal() {
        try {
            Context c = new InitialContext();
            return (CartBeanLocal) c.lookup("java:global/onlineBK/onlineBK-ejb/CartBean!stateless.CartBeanLocal");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

}
